import { Button, Form, Input, message } from "antd";
import { useNavigate } from "react-router-dom";
import { loginApi } from "../../../apis/login";
import { useState } from "react";
type FieldType = {
  email?: string;
};
function SignIn() {
  const navto = useNavigate();
  function to(url: string) {
    navto(url);
    setLoading(false);
  }
  let [Loading, setLoading] = useState<boolean>(false);
  const [messageApi, contextHolder] = message.useMessage();
  const onFinish = (values: any) => {
    openMessage("loading", "登录中", "loading");
    setLoading(true);
    loginApi(values).then((res: any) => {
      if (res.code === 200) {
        sessionStorage.setItem('accessToken',res.result!.accessToken)
        sessionStorage.setItem('refreshToken',`${res.result!.refreshToken}`)
        openMessage("success", res.msg, "loading", to, "/layout");
      } else {
        console.log(res);
        openMessage("error", res.msg, "loading");
      }
    })
  };
  // 弹框
  const openMessage = (
    type: any,
    msg: string,
    key?: string,
    callback?: Function,
    url?: string
  ) => {
    // 设置key才会干掉加载
      messageApi.open({
        key: key,
        type: type,
        content: msg,
        onClose() {
          callback ? callback(url!) : "";
          setLoading(false);
        },
      });
  };
  const onFinishFailed = (errorInfo: any) => {
    console.log(errorInfo);
  };

  return (
    <>
      {contextHolder}
      <div className="logintitle">
        <img src="../../../../public/login/3.svg" alt="" />
        <span>登录</span>
      </div>
      <Form
        layout="vertical"
        name="basic"
        style={{ width: "100%" }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item<FieldType>
          label={
            <label style={{ color: "#fff", fontWeight: 600 }}>Email</label>
          }
          name="email"
          rules={[{ required: true, message: "Please input your email!" }]}
        >
          <Input />
        </Form.Item>
        <Form.Item<FieldType>
          label={<label style={{ color: "#fff", fontWeight: 600 }}>密码</label>}
          name="password"
          rules={[{ required: true, message: "Please input your password!" }]}
        >
          <Input.Password />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" block loading={Loading}>
            <label style={{ fontWeight: "bold" }}>登录</label>
          </Button>
        </Form.Item>
      </Form>
      <div className="forgetPass" onClick={() => to("/login/forget_pass")}>
        忘记密码?
      </div>
      <div className="more">
        还没有账号?
        <span className="toregister" onClick={() => to("/login/sign_up")}>
          去注册
        </span>
      </div>
    </>
  );
}

export default SignIn;
